import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { ContractService } from './contract.service';
import { UseLog } from 'src/log/useLog.decorator';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { Contract } from './Contract.entity';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { In } from 'typeorm';

@Controller('api/contract')
@ApiTags("合同管理")
@UseGuards(AuthGuard("jwt"))
export class ContractController {
    constructor(
        private readonly contractService: ContractService
    ) { }

    @Get("get")
    @ApiOperation({ summary: "获取合同" })
    async get(
        @CurrentUser() user: UserSys
    ) {
        const data = await this.contractService.contract.find({
            order: {
                id: "desc"
            },
            relations: ["system"],
            where: {
                id: user.system.id
            }
        })
        return data
    }

    @Post("add")
    @UseLog("添加合同")
    add(
        @Body() body: Contract,
        @CurrentUser() user: UserSys
    ) {
        return this.contractService.contract.save(
            this.contractService.contract.create({
                system: user.system,
                ...body
            })
        )
    }

    @Post(":id/upd")
    @UseLog("修改合同")
    upd(
        @Param("id") id: number,
        @Body() body: Contract
    ) {
        return this.contractService.contract.update({
            id
        }, body)
    }

    @Post("del")
    @UseLog("删除合同")
    del(
        @Body() { ids },
        @CurrentUser() user: UserSys
    ) {
        return this.contractService.contract.delete({
            id: In(ids),
            system: {
                id: user.system.id
            }
        })
    }
}
